package com.heima.wemedia.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.JAXBUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.PageResponseResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.file.service.FileStorageService;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.wemedia.dto.WmMaterialDto;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.utils.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Resource
    private FileStorageService fileStorageService;

    /**
     * 图片上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile multipartFile) {
        //1.检查参数
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.上传图片到minIO中
        String originalFilename = multipartFile.getOriginalFilename();
        String postFix = StrUtil.subAfter(originalFilename, '.', true);
        String fileName = StrUtil.format("{}.{}", IdUtil.simpleUUID(), postFix);
        String fileId;
        try {
            fileId = fileStorageService.uploadImgFile("", fileName, multipartFile.getInputStream());
            log.info("上传图片到minIO中，fileId:{}", fileId);
        } catch (IOException e) {
            log.error("WmMaterialServiceImpl-上传文件失败");
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "上传文件失败");
        }

        //3.保存到数据库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);

        //4.返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材列表查询
     *
     * @param dto
     * @return
     */
    /**
     * 素材列表查询
     */
    @Override
    public PageResponseResult<List<WmMaterial>> findList(WmMaterialDto dto) {
        //1.检查参数
        dto.checkParam();
        //2.分页查询
        IPage<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = Wrappers.lambdaQuery();
        //是否收藏
        lambdaQueryWrapper.eq(ObjectUtil.equal(dto.getIsCollection(), 1), WmMaterial::getIsCollection, dto.getIsCollection());

        //按照用户查询
        lambdaQueryWrapper.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId());

        //按照时间倒序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        //查询数据
        super.page(page, lambdaQueryWrapper);

        //3.结果返回
        return PageResponseResult.<List<WmMaterial>>builder()
                .currentPage(dto.getPage())
                .size(dto.getSize())
                .total(Convert.toInt(page.getTotal()))
                .data(page.getRecords())
                .build();
    }

    /**
     * 图片删除
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteImage(Integer id) {
        return this.removeById(id);
    }

    /**
     * 收藏与取消
     *
     * @param id
     * @return
     */
    @Override
    public boolean changeStatus(Integer id) {
        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.<WmMaterial>lambdaQuery()
                .eq(WmMaterial::getId, id);
        WmMaterial wmMaterial = this.getOne(queryWrapper);
        if (ObjectUtil.equals(wmMaterial.getIsCollection(), 0)) {
            wmMaterial.setIsCollection(Convert.toShort(1));
        } else {
            wmMaterial.setIsCollection(Convert.toShort(0));
        }
        return this.updateById(wmMaterial);
    }
}


























